<template>
	<view class="page__content">
		<z-paging ref="paging" v-model="tableData" :auto="false" @query="getSearchList" auto-show-system-loading
			preload-page="20" :back-to-top-style="{ 'opacity':0.6 }">
			<!-- 顶部导航与搜索 -->
			<template #top>
				<view class="topBox">
					<up-navbar :fixed="false" :title="titleName + '筛选'" :autoBack="true" leftIconColor="#fff">
						<view slot="right">
							<text v-if="multiple" style="color: #fff;" @click="confirmMultipleSelect">确定</text>
						</view>
					</up-navbar>

					<view class="SearchBox" v-if="searchKey != 'none'">
						<up-search :showAction="true" v-model="param[searchKey]" @search="search" shape="square"
							:animation="false" :inputStyle="{fontSize: '24rpx'}">
							<template #action>
								<view class="x-c" style="width: 60rpx;">

									<uni-icons v-if="enableAddOption" color="#fff" @click="navigateToAddPage"
										type="plusempty" size="30"></uni-icons>

									<text @click="search" v-else style="color: #fff;font-size: 24rpx;">查询</text>
								</view>
							</template>
						</up-search>
					</view>
				</view>
			</template>


			<template v-for="(item,index) in tableData" :key="index">
				<up-cell :title="item[displayValue]" :disabled="item.disabled" size="large"
					@click="innerCellClick(item, index)" :titleStyle="{fontSize:'28rpx'}">
					<template #label>
						<view v-if="subText.length">
							<view v-for="row in subText" :key="row.labelKey">
								<view v-if="item[row.labelKey]"
									style="font-size: 28rpx; color: #999; margin-top: 8rpx;">
									<text>{{ row.label }} {{ item[row.labelKey] }}</text>
								</view>
							</view>
						</view>
					</template>

					<template #value>
						<checkbox v-if="multiple" :checked="item.checked" class="CheckBox"
							activeBackgroundColor="#51d0d0" activeBorderColor="#51d0d0" />

						<view v-else-if="!multiple && item.checked">
							<up-icon size="30" name="checkbox-mark" color="#12ce04" />
						</view>
					</template>
				</up-cell>
			</template>


			<template #bottom v-if="multiple || allowClear">
				<view class="page__content__bottom x-bc" :style="uni.$utils.disposeSafeBottomFun()">
					<template v-if="multiple">
						<view class="ChoiceNumBox">
							<text>已选：</text>
							<text class="Nums">{{selectedList.length}}</text>
							<text>项</text>
						</view>
					</template>

					<view class="x-ec">
						<template v-if="allowClear">
							<button class="content_bottom_danger_Btn CommonBtnSize" @click="clearSelection">清除</button>
						</template>

						<template v-if="multiple">
							<button class="content_bottom_primary_Btn CommonBtnSize"
								@click="confirmSelection">确定</button>
						</template>
					</view>
				</view>
			</template>

		</z-paging>

	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, nextTick } from 'vue';
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';

	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();


	defineOptions({
		options: {
			styleIsolation: 'shared'
		}
	})

	const baseScreenParm = mainStore.BaseScreenParm
	// 2. 将数据复制到页面自己的响应式对象中（使用 reactive，深层响应式）
	const pageData = reactive({
		// 解构并复制所有字段（浅拷贝，深层对象会引用原始数据，按需深拷贝）
		...baseScreenParm,
		// 单独处理嵌套的 serverSearch，确保嵌套对象也是响应式的
		serverSearch: {
			...baseScreenParm.serverSearch,
			format: { ...baseScreenParm.serverSearch.format } // 继续复制深层字段
		}
	});
	const {
		allowClear, // 清除按钮
		titleName,
		cmd, // 接口名
		listeningName, // 监听器
		multiple, // 是否开启多选
		enableAddOption, // 是否开启新增
		addOptionPath,
		serverSearch: { // 查询项
			format: { // 数据映射
				displayValue, // 显示值
				hiddenValue, // 隐藏值
				pageIndex, // 分页状态页码字段
				pageSize, // 分页状态每页数量字段
			},
			isLocal, // 是否启用本地数据
			localData, // 当开启本地数据时使用
			isPaging, //是否分页
			searchKey, //搜索关键词，应包含在param中
			subText,
			disabled, // 需要禁用的数据
			choiceData, // 选中数据
			choiceDataKey, // 选中数据的key
			isTree, // 是否开启树型下拉
		},
		// param // 传递参数
	} = pageData;

	let param = reactive({
		...pageData.param
	})

	interface pagingInstance {
		reload : () => void;
		refresh : () => void;
		complete : () => void;
		setLocalPaging : () => void;
	}
	let paging = ref<pagingInstance | any>(null);

	// 列表数据
	let tableData = ref<any>([]);

	// 选中数据
	let selectedList = ref<any>([]);
	let selectedID = ref<any>([]);

	// 当前属于多选状态
	if (multiple) {
		// 将数据传给选中数据数组
		selectedList.value = JSON.parse(JSON.stringify(choiceData));
		selectedID.value = toPrimitiveArray(JSON.parse(JSON.stringify(choiceData)), choiceDataKey);
	}

	/**
	 * 将数组转换为纯基础类型数组
	 * @param arr 输入数组，可以是基础类型数组或对象数组
	 * @param prop 可选参数，指定从对象中提取的属性名，不指定则取第一个属性
	 * @returns 纯基础类型数组
	 */
	function toPrimitiveArray(
		arr : any[],
		prop ?: string
	) : (string | number | boolean | symbol | bigint | null | undefined)[] {
		if (!Array.isArray(arr)) {
			throw new Error('输入必须是数组');
		}

		// 检查是否为基础类型数组
		const isPrimitive = arr.every(item => {
			const type = typeof item;
			return item === null || ['string', 'number', 'boolean', 'symbol', 'bigint', 'undefined'].includes(type);
		});

		// 如果是基础类型数组，直接返回
		if (isPrimitive) {
			return arr;
		}

		// 否则视为对象数组，进行转换
		return arr.map(item => {
			// 跳过null和undefined
			if (item === null || item === undefined) {
				return item;
			}

			// 处理对象类型
			if (typeof item === 'object') {
				// 如果指定了属性名且存在，则使用该属性值
				if (prop && prop in item) {
					return item[prop as keyof typeof item];
				}

				// 否则取第一个属性值
				const keys = Object.keys(item);
				if (keys.length > 0) {
					return item[keys[0] as keyof typeof item];
				}
			}

			// 无法转换的项返回null
			return null;
		});
	};

	// 跳转基础信息新增页面
	function navigateToAddPage() {

		let routes = getCurrentPages(); //当前页面栈
		let listenName = "listenName_baseScreen_" + routes.length;

		uni.navigateTo({
			url: addOptionPath + "?listen=" + listenName
		})
	};

	// 获取列表数据
	function getSearchList(pageNo : number) {
		// 判断是否走本地
		if (isLocal) {
			let backData = localData.map((item : any) => {
				const id = item[hiddenValue];
				return {
					...item,
					checked: id == choiceData
				}
			})
			paging.value.setLocalPaging(backData)
		} else {
			// request
			if (isPaging) {
				param[pageIndex] = pageNo;
			}
			request({
				config: {
				},
				url: cmd,
				method: 'POST',
				data: param,
				success(ret : any) {
					if (ret.status == 200) {
						const list = ret.data.ds.map((item : any) => {
							const id = item[hiddenValue];
							let checked = false;
							if (!multiple) {
								checked = id === choiceData;
							} else if (Array.isArray(selectedID.value)) {

								checked = selectedID.value.includes(id);

								// if (checked && !selectedList.value.some((i : any) => i[multiple] === id)) {
								// 	selectedList.value.push({
								// 		...item
								// 	});
								// }
							}
							let disabledType = false;
							// 判断是否存在disabled数据
							if (disabled.data.length) {

								if (disabled.data.includes((item[disabled.key]))) {
									disabledType = true;
								} else {
									disabledType = false;
								}
							}

							return {
								...item,
								checked,
								disabled: disabledType
							};
						});
						if (cmd == 'XGD_GetWorkByJobType') {
							console.log(list);
						}

						if (isPaging) {
							paging.value.complete(list);
						} else {
							paging.value.setLocalPaging(list);
						}

					} else {
						paging.value.complete(false);
					}
				},
				fail(err) {
					paging.value.complete(false);
				}

			});

		}
	};

	// 多选确认按钮
	function confirmMultipleSelect() {

	}

	// 搜索框查询
	function search() {
		console.log(1111);
		paging.value.reload();
	}

	// 单击数据行
	function innerCellClick(item : any, index : any) {
		if (item.disabled) return
		// 判断是否单选
		if (!multiple) {
			uni.$emit(listeningName, {
				multiple,
				titleName,
				data: item,
				index
			});
			uni.navigateBack();
		} else {
			item.checked = !item.checked;

			if (item.checked) {
				const exists = selectedList.value.some(i => i[hiddenValue] === item[hiddenValue]);
				if (!exists) {
					selectedList.value.push(item);
					selectedID.value.push(item[hiddenValue]);
				}
			} else {
				selectedList.value = selectedList.value.filter(i => i[hiddenValue] !== item[hiddenValue]);
				selectedID.value = selectedID.value.filter(i => i !== item[hiddenValue]);
			}
		}

	};

	// 清空选中数据
	function clearSelection() {

		if (!multiple) {
			uni.$emit(listeningName, {
				multiple,
				titleName,
				data: null,
				index: null
			});
			uni.navigateBack();
		} else {
			selectedList.value = []
			confirmSelection();

		}
	}

	// 多选确认按钮
	function confirmSelection() {
		uni.$emit(listeningName, {
			multiple,
			titleName,
			data: selectedList.value,
		});
		uni.navigateBack();
	}


	onLoad(() => {
	})
	onMounted(() => {
		nextTick(() => {
			getSearchList(1);
		})
	})

	onUnload(() => {
		mainStore.BaseScreenParm = {}
	});
</script>

<style lang="scss">
	.page__content {
		background-color: #f9f9f9;

		.SearchBox {
			background-color: #51d0d0;
			padding: 6px 10px;
		}

		.hoverCell {
			background-color: rgba(235, 0, 12, 0.2);
		}

		.selected-bar {
			padding: 10rpx;
			border-top: 1px solid #eee;
			background-color: #f9f9f9;
		}

		.selected-scroll {
			display: flex;
			flex-direction: row;
		}

		.selected-item {
			display: flex;
			align-items: center;
			background: #e6f7ff;
			border: 1px solid #91d5ff;
			border-radius: 16rpx;
			padding: 0 10rpx;
			margin-right: 10rpx;
			font-size: 12px;

			.text {
				margin-right: 6rpx;
			}
		}


		:deep(.u-cell__body) {
			padding: 26rpx 30rpx !important;
		}

		.page__content__bottom {
			background-color: #fff;
		}
	}

	/* #ifdef MP-WEIXIN */
	/* 复选框样式（保持原样） */
	:deep(.uni-checkbox-input) {
		border: 2px solid #d1d1d1 !important;
	}

	:deep(.uni-checkbox-input-checked) {
		background: #51d0d0;
		color: #fff !important;
		border-color: #51d0d0 !important;
	}

	// 复选框样式 End
	/* #endif */
</style>